// Copyright (c) 2022, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on('SRM Purchase Order', {

	onload: frm => {
		// 控制不允许新增行
		if (frm.doc.is_answer === 1) {
			frm.get_field('answer_subs').grid.cannot_add_rows = true;
			refresh_field('answer_subs');
		};
		// 隐藏删除行按钮
		$('*[data-fieldname="purchase_order_sub"]').find('.grid-remove-rows').hide();
		// 隐藏子表单[添加行]按钮
		// frm.get_field('purchase_order_sub').grid.cannot_add_rows = true
		// set_html(frm);
		// update_data(frm);
    },

	srm_supplier: function(frm) {
		frm.set_df_property("srm_supplier", "description", frm.doc.supplier_name);
	},

	refresh: function(frm) {
		// 隐藏子表中的"上传"按钮
		$(".grid-upload").hide();

		// 手动所采购订单号到ERP同步一次: 更新单据的关闭状态及行业务状态
		if (frappe.user.has_role('SRM Purchase')) {
			frm.add_custom_button(__('Sync'), () => {
				frappe.call({
					method: "get_po_from_erp",
					doc: frm.doc,
					freeze: true,
					freeze_message: __("正在同步ERP..."),
				}).then ((r) => {frm.refresh(); frappe.msgprint("从ERP同步完成!")})
			});
		}

		if (frappe.user.has_role('Admin') || frappe.user.has_role('Administrator'))
		{
			frm.add_custom_button(__('关闭答交'), () => {
				frm.set_value('is_answer', 1);
				frm.set_df_property('answer_subs', 'read_only', 1);
				// frm.save();
				frm.refresh();
				frappe.msgprint("关闭成功!不允许再操作答交明细!");
			},__('Answer'))
			frm.add_custom_button(__('反关闭答交'), () => {
				frm.set_value('is_answer', 0);
				frm.set_df_property('answer_subs', 'read_only', 0);
				// frm.save();
				frm.refresh();
				frappe.msgprint("反关闭成功!允许操作答交明细!");
			},__('Answer'))
	 	}

		// 一行行记录确认答交时，限制物料代码只能选择订单明细行中的物料范围
		frm.fields_dict['answer_subs'].grid.get_field('material_number').get_query = function(doc, cdt, cdn) {
			var materials = frm.doc.purchase_order_sub.map( item => { return item.material_number})
			// console.log(materials);
			var child = locals[cdt][cdn];
			// console.log(child);
			return {    
				//过滤条件
				filters:[
					['material_number', 'in', materials]
				]
			}
		};

		// 通过[默认]按钮，复制订单明细作为答交: 2023-03-21控制在九联不需要显示
		// if (frappe.user.has_role('Admin') || frappe.user.has_role('Administrator')) {
		// 	frm.fields_dict["purchase_order_sub"].grid.add_custom_button(__('Default Answer'), 
		// 		function() {
		// 			if (frm.doc.is_answer == 0) {
		// 				//循环子表orderitem
		// 				$.each(frm.doc.purchase_order_sub, function(i, d) {
		// 					// console.log(d)
		// 					d.answer_info = d.request_date + "/" + d.qty;
		// 					d.answer_qty = d.qty;
		// 				});
		// 				refresh_field("purchase_order_sub");
		// 				frm.dirty();
		// 				frm.save();
		// 			}
		// 			else if (frm.doc.is_answer == 1) {
		// 				frappe.throw("已经答交不允许再答交")
		// 			}
		// 	});
		// 	frm.fields_dict["purchase_order_sub"].grid.grid_buttons.find('.btn-custom').removeClass('btn-default').addClass('btn btn-primary');
		// }
		
		// 供应商用户确认是否接收订单 
		if (frappe.user.has_role('SRM Supplier') || frappe.user.has_role('Administrator'))
		{
			frm.add_custom_button(__('Accept By Supplier'), () => {
				if (!frm.doc.accept_by_supplier) {
					frappe.prompt([
						{
							label: 'Accept By Supplier',
							fieldname: 'selection',
							fieldtype: 'Select',
							options: ['', '接收', '拒绝'],
						},
						{
							label: 'Reason',
							fieldname: 'reason',
							fieldtype: 'Data',
							depends_on: "eval: doc.selection == '拒绝'",
							mandatory_depends_on: "eval: doc.selection == '拒绝'"
						},
					], (values) => {
						frappe.call({
							method: "confirm_accept_by_supplier",
							doc: frm.doc,
							args: { selection: values.selection, reject_reason: values.reject_reason},
							freeze: true,
							freeze_message: __("running..."),
							callback: function(r) {
								frm.refresh();
							}
						});
						console.log(values.selection);
					})
				}
				else {frappe.msgprint("已经确认不允许重复!")}
			})
		}
	}
	
});

frappe.ui.form.on('SRM Purchase Order Sub', {
	// answer按钮调用answer方法
	answer: function(frm, cdt, cdn){
		let d = locals[cdt][cdn]
		// 传参
		answer_data({
			frm: frm,
			cdt: cdt,
			cdn: cdn,
			row_name: d.name,
			assign_qty: d.qty,
			need_date: d.request_date,
			answer_info: d.answer_info,
			material_model: d.material_model,
		})
	},

	// roll_id(frm, cdt, cdn){       //字段值变更后触发这段代码执行
	// 	calculate_qty(frm, cdt, cdn)                             //调用公用函数    
	// },
	// qty(frm, cdt, cdn, fieldname){    //字段值变更后触发这段代码执行，初次设默认值时不触发这个代码
	// 	let row = locals[cdt][cdn];
	// 	// if (!row.verified_qty) frappe.model.set_value(cdt, cdn, 'verified_qty', row.claimed_qty)
	// 	calculate_qty(frm, cdt, cdn, 'claimed_qty')                             //调用公用函数    
	// },
});

frappe.ui.form.on('SRM Purchase Order Answer Sub', {
	// 新增行记录时自动复制上一行记录
	answer_subs_add(frm, cdt, cdn) {
		var last_row_index = frm.doc.answer_subs.length
		if (last_row_index > 0) {
			var last_row = frm.doc.answer_subs[last_row_index-2]
			var cur_row = frm.doc.answer_subs[last_row_index-1]
			cur_row.material_number = last_row.material_number
			cur_row.material_name = last_row.material_name
			cur_row.request_date = last_row.request_date
		}
	}
});

frappe.ui.form.on("SRM Purchase Order", "before_load", function(frm) {
	frappe.form.link_formatters['SRM Supplier'] = function(value, doc) {
		return value + ': ' + doc.supplier_name;
	}
});

const set_html = frm => {
	$("#html_items").remove();
	$(`
		<table id="subs" class="table table-bordered">
			<caption style="caption-side: top;">HTML Items</caption>
			<thead>
				<tr class="d-flex">
					<th class="col-4">Item</th>
					<th class="col-2">Quantity</th>
					<th class="col-3">Rate</th>
					<th class="col-3">Amount</th>
				</tr>
			</thead>
			<tbody>
				<tr v-cloak class="d-flex" v-for="(item, index) in items">
					<td class="col-4">{{ item.material_number }}</td>
					<td class="col-2">{{ item.qty }}</td>
					<td class="col-3">{{ item.price }}</td>
					<td class="col-3">{{ item.amount }}</td>
				</tr>
				<tr v-cloak v-if="items.length === 0 ">
					<td style="font-style: italic">No data.</td>
				</tr>
			</tbody>
		</table>
	`).appendTo(frm.fields_dict.html_items.wrapper);
  };
  
const update_data = frm => {
	const vm = new Vue({
		el: "#subs",
		data: {
			items: frm.doc.purchase_order_sub
		}
	});
  };

  // 答交方法
let answer_data = function(opts) {
	let frm = opts.frm;
	// 定义data变量
	let data = [];
	// 如果已经有答交明细则赋值data
	if (opts.answer_info) {
		// 获取已有的answer_info
		let answer_info_get = opts.answer_info;
		// 字符串split
		let d = answer_info_get.split(",");
		// forEach循环
		d.forEach((item) => {
			// 把answer_date和qty赋值到对象obj
			const obj = {"answer_date": item.split("/")[0], "qty": item.split("/")[1]}; 
			// 把obj push到data
			data.push(obj);
		});
	}
	// 如果没有答交明细(第一次答交),则data默认为assign_qty和need_date
	else {data = [{"answer_date": opts.need_date, "qty": opts.assign_qty}]}
	// 定义弹窗的子表字段(有参考价值)
	const fields = [{
		fieldtype:'Date',
		fieldname:"answer_date",
		in_list_view: 1,
		read_only: 0,
		disabled: 0,
		label: __('Date'),
	}, {
		fieldtype:'Float',
		fieldname:"qty",
		default: 0,
		read_only: 0,
		in_list_view: 1,
		label: __('Qty')
	}];
	// 定义Dialog
	const dialog = new frappe.ui.Dialog({
		title: __("Answer Submit"),
		// 定义弹窗的所有字段
		fields: [
			{
				fieldtype:'Data',
				fieldname:"row_name",
				default: opts.row_name,
				read_only: 1,
				hidden: 1,
				label: __('Qty')
			},
			{
				fieldtype:'Data',
				fieldname:"material_model",
				default: opts.material_model,
				read_only: 1,
				hidden: 0,
				label: __('Material Model')
			},
			{
				fieldtype:'Data',
				fieldname:"assign_qty",
				default: opts.assign_qty,
				read_only: 1,
				label: __('Assign Qty')
			},
			{
				fieldtype:'Date',
				fieldname:"need_date",
				default: opts.need_date,
				read_only: 1,
				label: __('Need Date')
			},
			// 定义弹窗中的表字段(很有参考价值)
			{
				fieldname: "answer_items",
				// 通过fieldtype定义
				fieldtype: "Table",
				label: "Items",
				cannot_add_rows: 0,
				in_place_edit: true,
				reqd: 1,
				data: data,
				get_data: () => {
					return data;
				},
				fields: fields
			},
		],
		primary_action: function() {
			// 变量定义
			let answer_info_confirm = [];
			let sum_answer_qty = 0;
			// 获取窗口中的子表明细
			const answer_items = this.get_values()["answer_items"].filter((item) => !!item.answer_date);
			answer_items.forEach((item) => {
				// 把子表行拼接: answer_date + "/" + item.qty
				// 并且push到answer_info_confirm
				if(item.answer_date < frappe.datetime.get_today()) {
					frappe.throw('日期不能小于今天')
				}
				else{
					answer_info_confirm.push(item.answer_date + "/" + item.qty );
					// 把子表的qty求sum,注意要flt函数
					// console.log(item.qty);
					sum_answer_qty += flt(item.qty);
				}
			})
			
			// 赋值
			if (sum_answer_qty <= opts.assign_qty) 
			{
				// 弃用
				// frappe.db.set_value('SRM Supply Plan Of Supplier OrderItem', opts.row_name, {'answer_info': answer_info_confirm.toString(), 'answer_qty': sum_answer_qty})
				// .then(r => {frm.reload_doc()})
				// 获取行记录
				let row_name = locals[opts.cdt][opts.row_name]
				row_name.answer_info = answer_info_confirm.toString();
				row_name.answer_qty = sum_answer_qty;
				frm.dirty();
				frm.save();
			}
			else{
				frappe.throw('超出需求总数量')
			}
			this.hide();
		},
		primary_action_label: __('Confirm')
	});

	dialog.show();
}


// 定义数量汇总公共函数
var calculate_qty = function(frm, fieldname){       //字段值变更后触发这段代码执行
	if (fieldname){
		let total_qty = frm.doc.purchase_order_sub.reduce((prev, cur)=>{return prev + (cur[fieldname] || 0)}, 0);
		let total_fieldname = "total_" + fieldname    
		frm.set_value(total_fieldname, total_qty);                                 
		frm.refresh_field(total_fieldname);
	}                              //刷新主表字段，显示更新后结果    
}

// 定义金额汇总公共函数
var calculate_amount = function(frm, fieldname){       //字段值变更后触发这段代码执行
	if (fieldname){
		let total_amount = frm.doc.purchase_order_sub.reduce((prev, cur)=>{return prev + (cur[fieldname] || 0)}, 0);
		let total_fieldname = "total_" + fieldname    
		frm.set_value(total_fieldname, total_amount);                                 
		frm.refresh_field(total_fieldname);
	}                              //刷新主表字段，显示更新后结果    
}




		// frm.set_df_property("srm_supplier", "description", frm.doc.supplier_name);
		// 供应商根据采购PO下推送货单
		// if (frappe.user.has_role('SRM Supplier')) {
		// 	frm.add_custom_button(__('下推送货单'), () => {
		// 			frm.call({
		// 				method: "get_po_from_erp",
		// 				doc: frm.doc,
		// 				freeze: true,
		// 				freeze_message: __("正在同步ERP..."),
		// 			}).then ((r) => {
		// 				frappe.model.open_mapped_doc({
		// 					method: "srm.srm.doctype.srm_purchase_order.srm_purchase_order.make_purchase_delivery_from_po",
		// 					frm: cur_frm,
		// 					freeze_message: __("Creating Purchase Receipt ...")
		// 				})
		// 			})
		// 	});
		// }